<?php
/**
 * Created by PhpStorm.
 * User: robot
 * Date: 2018-04-18
 * Time: 22:59
 */

namespace app\admin\controller;


use app\base\BaseController;
use app\base\model\Sort as SortModel;
use app\base\model\Article as ArticleModel;
use think\Loader;
use think\Request;
use think\Session;

class Publish extends BaseController
{
    /***
     * 输出视图
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {

        $this->assign('sort', SortModel::all());
        $this->assign('title', '发布文章');
        return $this->fetch();
    }

    /***
     * 添加文章接口
     * @return array
     */
    public function add()
    {
        $request = Request::instance();
        if (!$request->isAjax()) {
            return ['code'=>-1,'msg'=>'请求方式错误'];
        }
        $data = $request->param();
        $validate = Loader::validate('PublishValidate');
        if (!$validate->check($data)) {
            return ['code'=>-1,'msg'=>$validate->getError()];
        }
        $userid = Session::get('user')['userid'];

        $add = ArticleModel::create([
            'sort' => $data['sort'],
            'title' => $data['title'],
            'content' => $data['content'],
            'userid' => $userid,
        ]);

        if ($add) {
            return ['code'=>1, 'msg' => "添加成功，文章编号为：$add->articid"];
        } else {
            return ['code'=>-1,'msg'=>'添加失败'];
        }

    }

}